package com.hnjmxy.servlet;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	//	response.getWriter().append("Served at: ").append(request.getContextPath());
		//获取用户上传的文件信息
		Part part = request.getPart("myfile");
		String filename = part.getSubmittedFileName(); //获取上传的文件名称
		//创建upload文件夹
		String path=this.getServletContext().getRealPath("/upload");
		File f=new File(path);
		if(!f.exists()) {
			f.mkdir();
		}
		//准备好上传的文件名称，为了防止多个用户上传的文件名相同
		String name =UUID.randomUUID()+filename; //UUID产生一个固定长的随机数
		//真正的上传
		part.write(path+"/"+name);
		String ppath="/upload/"+name;//保存到数据表的文件路径

		}
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
